#include "CockpitPanelAdaptor.h"

#include <simodo/shell/access/RunnerManagement_interface.h>

#include <QtCore>

CockpitPanelAdaptor::CockpitPanelAdaptor(
    shell::Access_interface & shell)
    : _shell(shell)
{
    _widget = new CockpitView();

    auto send_message = []( shell::RunnerManagement_interface * rm
                          , QString key
                          , int value
                          )
    {
        if (rm == nullptr)
        {
            return;
        }

        QJsonObject jo;
        jo.insert("key", key);
        jo.insert("value", value);
        auto message_json = QJsonDocument(jo).toJson(QJsonDocument::Compact);

        rm->send(message_json);
    };

    connect( _widget
           , &CockpitView::pressKey
           , [this, send_message](QString key)
           {
               send_message(_shell.getRunnerManagement(), key, 1);
           });
    connect( _widget
           , &CockpitView::releaseKey
           , [this, send_message](QString key)
           {
               send_message(_shell.getRunnerManagement(), key, 0);
           });
}

CockpitPanelAdaptor::~CockpitPanelAdaptor()
{
}

QString CockpitPanelAdaptor::title() const
{
    return tr("Cockpit");
}

void CockpitPanelAdaptor::started() 
{
}

void CockpitPanelAdaptor::paused() 
{
}

void CockpitPanelAdaptor::stoped()
{
}

bool CockpitPanelAdaptor::acceptData(const QString & func, QVector<QString> & data)
{
    if (func == "init") {
        if (data.size() != 1)
            return false;

        _shell.risePanel("Cockpit", "");
        return true;
    }

    if (func == "setPosition") {
        if (data.size() == 0 || data.size() % 3 != 0)
            return false;

        auto end_it = data.end();
        _widget->handleChangedHeight((end_it - 2)->toDouble());
        return true;
    }

    if (func == "setAngles") {
        if (data.size() == 0 || data.size() % 3 != 0)
            return false;

        auto end_it = data.end();
        _widget->handleChangedAngles((end_it - 3)->toDouble(), (end_it - 2)->toDouble(), (end_it - 1)->toDouble());
        return true;
    }

    if (func == "setVerticalSpeedSlide") {
        if (data.size() == 0 || data.size() % 2 != 0)
            return false;

        auto end_it = data.end();
        _widget->handleChangedVerticalSpeedSlide((end_it - 2)->toDouble(), (end_it - 1)->toDouble());
        return true;
    }

    if (func == "setSpeed") {
        if (data.size() == 0)
            return false;

        _widget->handleChangedSpeed(data.last().toDouble());
        return true;
    }

    return false;
}


